import { constantRoutes } from '@/router'
import { deepClone } from '@/utils'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}
function _import(str) { // views文件夹下的Home组件，传入的格式为 'Home'
  return function(resolve) {
    require([`@/views/${str}.vue`], resolve)
  }
}
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === '/layout') {
        route.component = () => import('@/layout')
      } else {
        const filePath = route.component // 所有filePath 都是填写@/views之后的路径
        route.component = _import(filePath) // 核心代码，必须这种格式写，否则报错
      }
    }
    if (route.children && route.children.length) { // 递归处理
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })

  return accessedRouters
}

function filterMenu(routes) {
  for (let i = 0; i < routes.length; i++) {
    const route = routes[i]
    if (route.path == '/') {
      return route.children
    }
  }
}

const state = {
  routes: [],
  addRoutes: [],
  menus: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_MENUS: (state, routes) => {
    state.menus = routes
  }
}

const actions = {
  generateRoutes({ commit }, { roles, menus }) {
    return new Promise(resolve => {
      let accessedRoutes // 处理之后最终动态添加的路由
      const initMenus = deepClone(menus) // 深度复制对象
      const wholeMenus = filterMenu(initMenus) // 登陆之后的菜单,先对数据做处理，后期由后端传值解决

      const dynamicRoutes = filterAsyncRouter(menus)// 需要解决后端传component为字符串的问题
      if (roles.includes('admin')) { //        *************角色处理，这边后面要重新修改*******
        accessedRoutes = dynamicRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(dynamicRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes) // 只存储了符合角色的路由信息
      commit('SET_MENUS', wholeMenus) // 把全部的路由信息保存在这里
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
